/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package theserver;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 * @author Emma
 */
public class ConnectToDevice {

	private ObjectOutputStream	objectOutputStream;


	public synchronized void Connect(ArrayList<DeviceList> deviceLists) {
		System.err.println("Connect devicelist i connecttodevice");
		String host = "";
		Long now = new Date().getTime();
		System.err.println(now);
		int port = 0;
		for (int i = 0; i < deviceLists.size(); i++) {
			for (int j = 0; j < deviceLists.get(i).size(); j++) {
				// checks if the current time is less than 5 minutes difference
				// to the connected device's lastseen Timestamp -
				// if so then creates a socket and sends the information to that
				// device
				Long then = deviceLists.get(i).get(j).getLastSeen().getTime();
				if (now - then < 1000 * 60 * 5) {
					System.err.print(now.toString() + " - " + then.toString()
							+ " = ");
					System.err.println(now - then);
					try {
						port = deviceLists.get(i).get(j).getPort();
						host = deviceLists.get(i).get(j).getIpAddress();
						System.err.println(deviceLists.get(i).get(j).getOwner()
								+ " @ " + host + ": " + port);
						Socket socket = new Socket(host, port);
						objectOutputStream = new ObjectOutputStream(
								new BufferedOutputStream(socket
										.getOutputStream()));
						objectOutputStream.writeObject(deviceLists.get(i));
						objectOutputStream.flush();
					} catch (ConnectException ce) {
						System.err.println("Could not connect to phone: "
								+ host + ":" + port);
					} catch (UnknownHostException ex) {
						Logger.getLogger(ConnectToDevice.class.getName()).log(
								Level.SEVERE, null, ex);
					} catch (IOException ex) {
						Logger.getLogger(ConnectToDevice.class.getName()).log(
								Level.SEVERE, null, ex);
					}
				}

			}
		}
	}
    public synchronized void Connect(VenueList ven, String host, int port){
        try {
            Socket socket = new Socket(host, port);
            ObjectOutputStream oos = new ObjectOutputStream(
							new BufferedOutputStream(socket.getOutputStream()));
					oos.writeObject(ven);
                    oos.flush();
            System.err.println("Server sent VenueList");
        } catch (UnknownHostException ex) {
            Logger.getLogger(ConnectToDevice.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ConnectToDevice.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}
